<template>
  <div class="player-compensation-manage">
    <h2>玩家补偿管理</h2>
    <el-table :data="compensations" style="width: 100%" border>
      <el-table-column prop="id" label="补偿记录ID" align="center"></el-table-column>
      <el-table-column prop="playerId" label="玩家ID" align="center"></el-table-column>
      <el-table-column prop="itemType" label="道具类型" align="center"></el-table-column>
      <el-table-column prop="amount" label="补偿数量" align="center"></el-table-column>
      <el-table-column prop="reason" label="补偿原因" align="center"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px;">
      <el-button type="primary" @click="showCreateDialog">发放补偿</el-button>
      <el-button @click="fetchAllCompensations">查询所有补偿记录</el-button>
      <el-input
          v-model="searchPlayerId"
          placeholder="按玩家ID筛选"
          style="width: 200px; margin-left: 10px"
          @keyup.enter="fetchCompensationsByPlayerId"
      />
      <el-input
          v-model="searchItemType"
          placeholder="按道具类型筛选"
          style="width: 200px; margin-left: 10px"
          @keyup.enter="fetchCompensationsByItemType"
      />
    </div>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      />
    </div>

    <!-- 补偿表单对话框 -->
    <el-dialog title="发放玩家补偿" v-model="dialogVisible" width="30%">
      <el-form :model="compensationForm" :rules="rules">
        <el-form-item label="玩家ID">
          <el-input v-model="compensationForm.playerId" />
        </el-form-item>
        <el-form-item label="道具类型">
          <el-input v-model="compensationForm.itemType" />
        </el-form-item>
        <el-form-item label="补偿数量">
          <el-input v-model="compensationForm.amount" />
        </el-form-item>
        <el-form-item label="补偿原因">
          <el-input v-model="compensationForm.reason" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑补偿对话框 -->
    <el-dialog title="编辑玩家补偿记录" v-model="editDialogVisible" width="30%">
      <el-form :model="editCompensationForm" :rules="rules">
        <el-form-item label="玩家ID">
          <el-input v-model="editCompensationForm.playerId" disabled />
        </el-form-item>
        <el-form-item label="道具类型">
          <el-input v-model="editCompensationForm.itemType" />
        </el-form-item>
        <el-form-item label="补偿数量">
          <el-input v-model="editCompensationForm.amount" />
        </el-form-item>
        <el-form-item label="补偿原因">
          <el-input v-model="editCompensationForm.reason" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateCompensation">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";
import dayjs from "dayjs";

const compensations = ref([]);
const loading = ref(false);
const searchPlayerId = ref('');
const searchItemType = ref('');

const dialogVisible = ref(false);
const editDialogVisible = ref(false);

const compensationForm = ref({
  id: null,
  playerId: '',
  itemType: '',
  amount: '',
  reason: ''
});

const editCompensationForm = ref({
  id: null,
  playerId: '',
  itemType: '',
  amount: '',
  reason: ''
});

// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 表单验证规则
const rules = {
  playerId: [{ required: true, message: '请输入玩家ID', trigger: 'blur' }],
  itemType: [{ required: true, message: '请输入道具类型', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入补偿数量', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入补偿原因', trigger: 'blur' }]
};

const formatDate = (dateString) => {
  if (!dateString) return '无';
  try {
    return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
  } catch (error) {
    return '时间格式错误';
  }
};

// 获取所有补偿记录（分页）
const fetchAllCompensations = async () => {
  try {
    loading.value = true;
    const response = await request.get('/customer-service/player-compensations', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        playerId: searchPlayerId.value,
        itemType: searchItemType.value
      }
    });
    if (response.data && response.data.records) {
      compensations.value = response.data.records.map(compensation => ({
        ...compensation,
        createTime: compensation.createTime ? dayjs(compensation.createTime).format('YYYY-MM-DD HH:mm:ss') : null
      }));
      total.value = response.data.total;
    } else {
      compensations.value = [];
      total.value = 0;
    }
    ElMessage.success('获取所有补偿记录成功');
  } catch (error) {
    console.error('获取所有补偿记录失败:', error);
    ElMessage.error('获取所有补偿记录失败: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

// 根据玩家ID获取补偿记录
const fetchCompensationsByPlayerId = async () => {
  const playerId = searchPlayerId.value.trim();
  if (!playerId) {
    ElMessage.warning('请输入玩家ID');
    return;
  }
  try {
    loading.value = true;
    const response = await request.get(`/customer-service/player-compensations/${playerId}`, {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    });
    if (response.data) {
      compensations.value = response.data.map(compensation => ({
        ...compensation,
        createTime: compensation.createTime ? dayjs(compensation.createTime).format('YYYY-MM-DD HH:mm:ss') : null
      }));
      total.value = response.data.length;
    } else {
      compensations.value = [];
      total.value = 0;
    }
    ElMessage.success(`获取玩家ID为 ${playerId} 的补偿记录成功`);
  } catch (error) {
    console.error('获取补偿记录失败:', error);
    ElMessage.error('获取补偿记录失败: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

// 根据道具类型获取补偿记录
const fetchCompensationsByItemType = async () => {
  const itemType = searchItemType.value.trim();
  if (!itemType) {
    ElMessage.warning('请输入道具类型');
    return;
  }
  try {
    loading.value = true;
    const response = await request.get('/customer-service/player-compensations', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        itemType: itemType
      }
    });
    if (response.data && response.data.records) {
      compensations.value = response.data.records.map(compensation => ({
        ...compensation,
        createTime: compensation.createTime ? dayjs(compensation.createTime).format('YYYY-MM-DD HH:mm:ss') : null
      }));
      total.value = response.data.total;
    } else {
      compensations.value = [];
      total.value = 0;
    }
    ElMessage.success(`获取道具类型为 ${itemType} 的补偿记录成功`);
  } catch (error) {
    console.error('获取补偿记录失败:', error);
    ElMessage.error('获取补偿记录失败: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

// 显示创建对话框
const showCreateDialog = () => {
  dialogVisible.value = true;
  compensationForm.value = {
    id: null,
    playerId: '',
    itemType: '',
    amount: '',
    reason: ''
  };
};

// 显示编辑对话框
const showEditDialog = (compensation) => {
  editDialogVisible.value = true;
  editCompensationForm.value = {
    ...compensation,
    createTime: compensation.createTime ? dayjs(compensation.createTime).format('YYYY-MM-DD HH:mm:ss') : null
  };
};

// 提交发放补偿表单
const submitForm = async () => {
  try {
    const response = await request.post('/customer-service/player-compensations', compensationForm.value);
    if (response.code === 200) {
      ElMessage.success('发放补偿成功');
      dialogVisible.value = false;
      // 刷新补偿记录列表
      await fetchAllCompensations();
    } else {
      ElMessage.error(response.message || '发放补偿失败');
    }
  } catch (error) {
    console.error('发放补偿出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

// 提交编辑补偿表单
const updateCompensation = async () => {
  try {
    const response = await request.put('/customer-service/player-compensations', editCompensationForm.value);
    if (response.code === 200) {
      ElMessage.success('更新补偿记录成功');
      editDialogVisible.value = false;
      // 刷新补偿记录列表
      await fetchAllCompensations();
    } else {
      ElMessage.error(response.message || '更新补偿记录失败');
    }
  } catch (error) {
    console.error('更新补偿记录出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

// 删除补偿记录
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该补偿记录吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await request.delete(`/customer-service/player-compensations/${id}`);
    if (response.code === 200) {
      ElMessage.success('删除补偿记录成功');
      // 刷新补偿记录列表
      await fetchAllCompensations();
    } else {
      ElMessage.error(response.message || '删除补偿记录失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除补偿记录出错，请检查控制台日志');
    }
  }
};

// 分页事件处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchAllCompensations();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchAllCompensations();
};

onMounted(() => {
  fetchAllCompensations();
});
</script>

<style scoped>
.player-compensation-manage {
  padding: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>